/**
 * 
 */
package by.wind.drebedengi;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import com.j256.ormlite.android.apptools.OrmLiteBaseTabActivity;

import by.wind.drebedengi.asynctask.AbstractTask;
import by.wind.drebedengi.asynctask.AsyncTaskManager;
import by.wind.drebedengi.asynctask.OnTaskCompleteListener;
import by.wind.drebedengi.asynctask.ReportingAllAsyncTask;
import by.wind.drebedengi.asynctask.UploadAsyncTask;
import by.wind.drebedengi.database.MyDatabaseHelper;
import by.wind.drebedengi.datalayer.Constants;
import by.wind.drebedengi.datalayer.bean.Login;
import by.wind.drebedengi.asynctask.UpgradeAsyncTask;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TabHost;
import android.widget.Toast;

/**
 * @author wind
 *
 */
public class MainActivity extends OrmLiteBaseTabActivity<MyDatabaseHelper> implements OnTaskCompleteListener {
	
	private String TAB_ACTIVITY_ONE;
	private String TAB_ACTIVITY_TWO;
	private String TAB_ACTIVITY_THREE;
	
	private AsyncTaskManager itsAsyncTaskManager;
	
	 // Our handler for received Intents. This will be called whenever an Intent
    // with an action named "custom-event-name" is broadcasted.
    public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("message");
        Log.d("receiver", "Got message: " + message);
        
        OutgoingActivity outgoingActivity = (OutgoingActivity) MainActivity.this.getLocalActivityManager().getActivity(TAB_ACTIVITY_ONE);
        Log.e("MainActivity","outgoingActivity="+outgoingActivity);
        if (outgoingActivity != null)
        	outgoingActivity.loadFormData();
        ReportingActivity reportingActivity = (ReportingActivity)  MainActivity.this.getLocalActivityManager().getActivity(TAB_ACTIVITY_THREE);
        Log.e("MainActivity","reportingActivity="+reportingActivity);
        if (reportingActivity != null) {
    		itsAsyncTaskManager = new AsyncTaskManager(MainActivity.this, reportingActivity);
    		itsAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
        	itsAsyncTaskManager.setupTask(new ReportingAllAsyncTask(reportingActivity));
        }
        IncomingActivity incomingActivity = (IncomingActivity)  MainActivity.this.getLocalActivityManager().getActivity(TAB_ACTIVITY_TWO);
        Log.e("MainActivity","incomingActivity="+incomingActivity);
        if (incomingActivity != null) {
        	incomingActivity.loadFormData();
        }
        
      }
    };
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.v("MainActivity", "Service started..");
		switch(item.getItemId()) {
		case R.id.sync_item:
			itsAsyncTaskManager = new AsyncTaskManager(MainActivity.this, MainActivity.this);
    		itsAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
			itsAsyncTaskManager.setupTask(new UpgradeAsyncTask(this));
			Log.v("MainActivity", "Service UpgradeService started..");
			break;
		case R.id.upload_item:
			itsAsyncTaskManager = new AsyncTaskManager(MainActivity.this, MainActivity.this);
    		itsAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
			itsAsyncTaskManager.setupTask(new UploadAsyncTask(MainActivity.this));
			Log.v("MainActivity", "Service UploadService started..");
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		TAB_ACTIVITY_ONE = getString(R.string.tab_sub);
		TAB_ACTIVITY_TWO = getString(R.string.tab_add);
		TAB_ACTIVITY_THREE = getString(R.string.tab_report);
		ArrayList<Login> loginList = (ArrayList<Login>) getHelper().getLoginDataDao().queryForAll();
		if (loginList.size()==0)
		{
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			return;
			
		} else
		{
			for(Login element : loginList) {
				Constants.LOGIN_VALUE = element.getLogin();
				Constants.PASS_VALUE = element.getPassword();
				break;
			}
		}
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    setContentView(R.layout.main);
	    itsAsyncTaskManager = new AsyncTaskManager(MainActivity.this, MainActivity.this);
		itsAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
	    Resources res = getResources(); // Resource object to get Drawables
	    TabHost itsTabHost = getTabHost();  // The activity TabHost
	    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
	    Intent intent;  // Reusable Intent for each tab

	    // Create an Intent to launch an Activity for the tab (to be reused)
	    intent = new Intent().setClass(this, OutgoingActivity.class);

	    // Initialize a TabSpec for each tab and add it to the TabHost
	    spec = itsTabHost.newTabSpec(TAB_ACTIVITY_ONE).setIndicator(TAB_ACTIVITY_ONE,
	                      res.getDrawable(R.drawable.ic_tab_sub))
	                  .setContent(intent);
	    itsTabHost.addTab(spec);
	    
	 // Do the same for the other tabs
	    intent = new Intent().setClass(this, IncomingActivity.class);
	    spec = itsTabHost.newTabSpec(TAB_ACTIVITY_TWO).setIndicator(TAB_ACTIVITY_TWO,
	                      res.getDrawable(R.drawable.ic_tab_add))
	                  .setContent(intent);
	    itsTabHost.addTab(spec);
	    
	    intent = new Intent().setClass(this, ReportingActivity.class);
	    spec = itsTabHost.newTabSpec(TAB_ACTIVITY_THREE).setIndicator(TAB_ACTIVITY_THREE,
	    				  res.getDrawable(R.drawable.ic_tab_report))
	    			   .setContent(intent);
	    itsTabHost.addTab(spec);
	    itsTabHost.setCurrentTabByTag(TAB_ACTIVITY_TWO);
	    itsTabHost.setCurrentTabByTag(TAB_ACTIVITY_THREE);
	    itsTabHost.setCurrentTabByTag(TAB_ACTIVITY_ONE);

	    if (!getHelper().isRecordsExists() && getLastNonConfigurationInstance() == null) {
	    	itsAsyncTaskManager = new AsyncTaskManager(MainActivity.this, MainActivity.this);
    		itsAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
	    	itsAsyncTaskManager.setupTask(new UpgradeAsyncTask(this));
			Log.v("MainActivity", "Service UpgradeService started..");
	    } else if (getHelper().isRecordsExists()){
    		 ReportingActivity reportingActivity = (ReportingActivity)  MainActivity.this.getLocalActivityManager().getActivity(TAB_ACTIVITY_THREE);
    	        Log.e("MainActivity","reportingActivity="+reportingActivity);
    	        if (reportingActivity != null) {
    	    		itsAsyncTaskManager = new AsyncTaskManager(MainActivity.this, reportingActivity);
    	    		itsAsyncTaskManager.handleRetainedTask(getLastNonConfigurationInstance());
    	        	itsAsyncTaskManager.setupTask(new ReportingAllAsyncTask(reportingActivity));
    	        }
	    }
	}
	
	@Override
	protected void onPause() {
		LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
		super.onPause();
	}
	
	protected void onResume() {
		LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
                new IntentFilter("custom-event-name"));
		super.onResume();
	}
	
	@Override
    public Object onRetainNonConfigurationInstance() {
		return itsAsyncTaskManager.retainTask();
    }

	@Override
	public void onTaskComplete(AbstractTask task) {
		if (task.isCancelled()) {
		    // Report about cancel
		    Toast.makeText(this, R.string.task_cancelled, Toast.LENGTH_LONG)
			    .show();
		} else {
		try {
			// Task is not completed
			if (!task.get())
			{
				//Network is not available
				if (!task.isNetworkAvailable()) {
					Toast.makeText(this, getString(R.string.offline_mode), Toast.LENGTH_SHORT).show();
				}
				else
				{
					AlertDialog.Builder b = new AlertDialog.Builder(this);
					b.setTitle(android.R.string.dialog_alert_title);
					b.setMessage(task.onErrorMessage());
					b.setPositiveButton(getString(android.R.string.ok),
			            new DialogInterface.OnClickListener()
			            {
			                @Override
			                public void onClick(DialogInterface dlg, int arg1)
			                {
			                    dlg.dismiss();
			                }
			            });
					b.create().show();
				}
			}
			Intent intent = new Intent("custom-event-name");
			// You can also include some extra data.
			intent.putExtra("message", "This is my message!");
			LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	}
}
